# -*- coding: utf-8 -*-
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from register.forms import RegisterForm

def register(request, success_url=None, template_name='register.html'):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            new_user = authenticate(username=form.cleaned_data["username"], password=form.cleaned_data["password"])
            login(request, new_user)
            return HttpResponseRedirect(success_url or reverse('register_ok'))
    else:
        form = RegisterForm()
    return render_to_response(template_name, { 'form': form }, context_instance=RequestContext(request))
